package com.example.chatImage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageTest {

    private static final String API_KEY = "22071a082822f9044ffbde9cc58e28b7";
    private static final String GET_TOKEN = "https://flagopen.baai.ac.cn/flagStudio/auth/getToken?apikey=";
    private static final String IMAGE = "https://flagopen.baai.ac.cn/flagStudio/v1/text2img";

    //获取json
    public static String getToken() {
        HttpRequest get = HttpUtil.createGet(GET_TOKEN + API_KEY);
        get.header("Accept", "application/json");
        get.contentType("application/json");
        HttpResponse response = get.execute();
        Token token = JSONUtil.toBean(response.body(), Token.class);
        System.out.println(response.body());
        return token.getData().getToken();
    }

    //文字--->图片
    public static String getImageByPrompt(ImageParam param) {
        HttpRequest post = HttpUtil.createPost(IMAGE);
        post.body(JSONUtil.toJsonPrettyStr(param));
        System.out.println(JSONUtil.toJsonPrettyStr(param));
        post.contentType("application/json");
        post.header("Accept", "application/json");
        post.header("token", getToken());
        post.timeout(10);
        HttpResponse response;
        try {
            response = post.execute();
        } catch (Exception e) {
            return e.getMessage();
        }
        ImageRes res = JSONUtil.toBean(response.body(), ImageRes.class);
        return res.getData();
    }

    /**
     * Base64转换为图片服务
     * targetPath  输出视频文件路径,不需要文件名
     * */
    public static File base64ToImg(String base64, String targetPath){
        if (base64 == null || "".equals(base64)){
            return null;
        }
        File file = null;
        FileOutputStream fops = null;
        base64 = base64.replace("data:image/jpeg;base64,","");
        byte[] buff = DatatypeConverter.parseBase64Binary(base64);
        try {
            file = File.createTempFile("图片Image",".jpeg",new File(targetPath));
            fops = new FileOutputStream(file);
            fops.write(buff);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("--------------------------------"+"图片转换完成"+"--------------------------------");
        return file;
    }


    public static void main(String[] args) {
        ImageParam param = new ImageParam();
        param.setPrompt("白马 花海 疾驰");
        System.out.println(getImageByPrompt(param));
//        base64ToImg("", "C:\\Users\\admin\\Desktop");
    }
}
